package com.bookmngsys.dao;

import com.bookmngsys.entity.BorrowHistory;
import com.bookmngsys.entity.ReservationHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

public interface ReservationHistoryDao extends JpaRepository<ReservationHistory, String> {


    @Query(value = "select * from reservation_history", nativeQuery = true)
    ArrayList<ReservationHistory> getAllReservationHistory();

    @Query(value = "select * from reservation_history where reader_id = :readerId", nativeQuery = true)
    ArrayList<ReservationHistory> getAllReservationHistoryByReaderId(Integer readerId);

    @Query(value = "select * from reservation_history where reader_id = :readerId and isbn = :isbn and book_id = :bookId and reserve_date = :reserveDate and is_used = false and is_cancelled = false", nativeQuery = true)
    ReservationHistory findValidReservation(Integer readerId, String isbn, Integer bookId, Long reserveDate);

    @Transactional
    @Modifying
    @Query(value = "UPDATE borrow_history SET is_returned = true where book_id  = :bookId and (is_used is null or is_used = false) and reserve_date + 3600 * 1000 * 4 >= :curTime", nativeQuery = true)
    void setIsUsed(Integer bookId, Long curTime);


}
